<template>
  <div style="overflow-y: auto">
    <Form>
      <FormItem label="">
        <Button type="primary" @click="openModal(false)">新建申请</Button>
      </FormItem>
    </Form>
    <Table :data="applyData" :columns="columns"  style="overflow-y: auto" />
    <Page style="margin-top: 10px" :total="total" :current="curPage" :page-size="pageSize" @on-change="changePage" />
    <Modal width="600" v-model="showModal">
      <template slot="header">
        <span>{{ this.isUpdateOpt ? '编辑申请' : '新建申请' }}</span>
      </template>

      <Form :label-width="100">
        <FormItem label="申请订单编号">
          <Input style="width: 400px" :value="formItem.inputFormNum == null ? '自动生成' : formItem.inputFormNum" disabled />
        </FormItem>
        <FormItem label="申请具体描述">
          <Input style="width: 400px" type="textarea" v-model="formItem.instruction" />
        </FormItem>
        <FormItem label="申请拨款">
          <InputNumber style="width: 400px" v-model="formItem.allowTotal" />
        </FormItem>
      </Form>

      <template slot="footer">
        <Button type="primary" @click="add">提交</Button>
        <Button @click="closeModal">取消</Button>
      </template>
    </Modal>
    <Modal width="800" v-model="showDetailModal">
      <template slot="header">
        <span>填写详细进货单</span>
      </template>

      <Form :label-width="100">
        <FormItem v-for="(item, index) in detailForm" :key="index" :label="`商品${index+1}`">
          <Form inline>
            <FormItem label="商品名">
              <Input v-model="item.name" />
            </FormItem>
            <FormItem label="商品单价">
              <InputNumber v-model="item.price" />
            </FormItem>
            <FormItem label="商品数量">
              <InputNumber :min="0" v-model="item.number" :precision="0" />
            </FormItem>
            <FormItem label="状态">
              <Select v-model="item.status">
                <Option :value="0">未入库</Option>
                <Option :value="2">已入库</Option>
              </Select>
            </FormItem>
            <FormItem label="操作">
              <Button :disabled="updateDetailItems.length > index" type="error" @click="detailForm.splice(index, 1)">del</Button>
            </FormItem>
          </Form>
        </FormItem>
        <FormItem label="">
          <Button type="dashed" @click="detailForm.push({name: '',price: 0,number: 1,status: 0})">add</Button>
        </FormItem>
      </Form>

      <template slot="footer">
        <Button type="primary" @click="addDetail">提交</Button>
        <Button @click="closeDetailModal">取消</Button>
      </template>
    </Modal>
  </div>
</template>

<script>
import Api from '@/api/purchase'
import dayjs from 'dayjs'
import {Storage} from "@/utils/storage";
export default {
  name: "apply",
  data () {
    return {
      applyData: [],
      columns: [
        { title: 'ID', key: 'id', align: 'center' },
        { title: '申请订单编号', key: 'inputFormNum', align: 'center' },
        { title: '申请人ID', key: 'requestManId', align: 'center' },
        { title: '申请描述', key: 'instruction', align: 'center' },
        { title: '申请金额', key: 'allowTotal', align: 'center' },
        {
          title: '申请状态',
          key: 'formStatus',
          align: 'center',
          render: (h, params) => {
            const status = {
              1: '申请未处理',
              2: '退回修改',
              3: '审批通过',
              4: '商品已入库'
            }
            return h('span', status[params.row.formStatus])
          }
        },
        {
          title: '申请时间',
          align: 'center',
          render: (h, params) => {
            return h('span', dayjs(params.row.createTime).format('YYYY-MM-DD HH:mm:ss'))
          }
        },
        {
          title: '操作',
          align: 'center',
          width: '300',
          render: (h, params) => {
            const detail = h(
                'Button', {
                  props: {
                    type: 'primary',
                    disabled: ![3].includes(params.row.formStatus)
                  },
                  on: {
                    click: () => {
                      Api.getDetailItems(params.row.inputFormNum).then(res => {
                        this.detailForm = [
                            ...res.data.data
                        ]
                        const length = this.detailForm.length
                        this.updateDetailItems = [...this.detailForm]
                        console.log(this.updateDetailItems)
                        if (length === 0) {
                          this.detailForm.push({
                            name: '',
                            price: 0,
                            number: 1,
                            status: 0
                          })
                        }
                        this.curInputFormNum = params.row.inputFormNum
                        this.openDetailModal()
                      })
                    }
                  }
                }, '填写详细进货单'
            )
            const enter = h(
                'Button', {
                  props: {
                    type: 'primary',
                    disabled: params.row.formStatus !== 3
                  },
                  style: {
                    marginLeft: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '确认进货',
                        content: '真的要确认进货吗？',
                        onOk: () => {
                          Api.updateStatus(params.row.inputFormNum).then(() => {
                            this.$Message.success('进货成功')
                            this.list()
                          })
                        }
                      })
                    }
                  }
                }, '确认进货'
            )
            const edit = h(
                'Button',   {
                  style: {
                    marginLeft: '5px',
                    marginTop: '5px'
                  },
                  props: {
                    type: 'primary',
                    disabled: [3, 4].includes(params.row.formStatus)
                  },
                  on: {
                    click: () => {
                      this.openModal(true)
                      this.settingData(params.row)
                    }
                  }
                },
                '编辑'
            )
            const del = h(
                'Button', {
                  style: {
                    marginLeft: '5px',
                    marginTop: '5px'
                  },
                  props: {
                    type: 'error',
                    disabled: [3, 4].includes(params.row.formStatus)
                  },
                  on: {
                    click: () => {
                      this.delete(params.row)
                    }
                  }
                },
                '删除'
            )
            return h('div', [detail, enter, edit, del])
          }
        }
      ],
      pageSize: 20,
      curPage: 1,
      total: 0,
      formItem: {
        allowTotal: 1,
        instruction: ''
      },
      showModal: false,
      isUpdateOpt: false,
      showDetailModal: false,
      detailForm: [],
      updateDetailItems: [],
      addDetailItems: [],
      curInputFormNum: null
    }
  },
  mounted () {
    this.list()
  },
  methods: {
    list () {
      Api.applyList({ pageSize: this.pageSize, curPage: this.curPage }).then(res => {
        const req = res.data
        if (req.resultCode !== 200) {
          this.$Message.error(req.message)
        }
        this.total = req.data.total
        this.applyData = req.data.result
      })
    },
    changePage (i) {
      this.curPage = i
      this.list()
    },
    openModal (isUpdate) {
      this.isUpdateOpt = isUpdate
      this.showModal = true
    },
    closeModal () {
      this.formItem = {
        allowTotal: 1,
        instruction: ''
      }
      this.showModal = false
    },
    add () {
      if (this.formItem.instruction == null || this.formItem.allowTotal == null || this.formItem.instruction === '') {
        this.$Message.error('参数缺失')
        return
      }
      if (!this.isUpdateOpt) {
        const userId = Storage.getItem('uid', 'user_info')
        Api.addApply({...this.formItem, status: 1, requestId: userId}).then(res => {
          const data = res.data
          if (data.resultCode !== 200) {
            this.$Message.error(data.message)
          } else {
            this.$Message.success('添加成功，请等待审核')
          }
          this.closeModal()
          this.changePage(1)
        })
      } else {
        Api.updateApply([{...this.formItem}]).then(res => {
          if (res.data.resultCode === 200) {
            this.$Message.success('更新成功')
          } else {
            this.$Message.error(res.data.message)
          }
          this.closeModal()
          this.list()
        })
      }
    },
    settingData (data) {
      this.formItem = {...data}
    },
    update () {
      if (this.formItem.instruction == null || this.formItem.allowTotal == null || this.formItem.instruction === '') {
        this.$Message.error('参数缺失')
        return
      }
      const userId = Storage.getItem('uid', 'user_info')
      Api.addApply({...this.formItem, status: 1, requestId: userId}).then(res => {
        const data = res.data
        if (data.resultCode !== 200) {
          this.$Message.error(data.message)
        } else {
          this.$Message.success('编辑成功')
        }
        this.closeModal()
        this.changePage(1)
      })
    },
    delete (data) {
      this.$Modal.confirm({
        title: '删除申请',
        content: '确定要删除商品吗？',
        onOk: () => {
          Api.deleteApply([{...data}]).then(res => {
            if (res.data.resultCode === 200) {
              this.$Message.success('删除成功')
            } else {
              this.$Message.error(res.data.message)
            }
            this.list(1)
          })
        }
      })
    },
    openDetailModal () {
      this.showDetailModal = true
    },
    closeDetailModal () {
      this.showDetailModal = false
      this.$nextTick(() => {
        this.detailForm = []
      })
    },
    addDetail () {
      this.detailForm.forEach(item => {
        item.inputFormNum = this.curInputFormNum
      })
      Api.updateDetailItems(this.updateDetailItems).then(() => {
        this.addDetailItems = [...this.detailForm.slice(this.updateDetailItems.length)]
        Api.reviewDetailItems(this.addDetailItems).then(() => {
          this.$Message.success('提交成功')
          this.closeDetailModal()
          this.list()
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
